package com.oa.service.impl;

import com.oa.common.utils.ValidateCode;
import com.oa.service.CommonService;
import com.oa.service.RedisService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.UUID;

@Service
public class CommonServiceImpl implements CommonService {

    @Qualifier("redisServiceImpl")
    @Autowired
    private RedisService redisService;

    private static final String TOKEN_NAME="villager_token";

    /** token 保存的时间 **/
    private static final int TOKEN_SAVE_TIME=20;

    @Override
    public void createImage(HttpServletRequest request, HttpServletResponse response) throws IOException {
        try {
            response.setContentType("image/jpeg");
            //禁止图像缓存。
            response.setHeader("Pragma", "no-cache");
            response.setHeader("Cache-Control", "no-cache");
            response.setDateHeader("Expires", 0);
            ValidateCode vCode = new ValidateCode(80,34);;
            redisService.saveVerify(request.getSession().getId(),vCode.getValidateCode());
            vCode.write(response.getOutputStream());
        } catch (IOException e) {
            e.printStackTrace();
        }  catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public String getToken(HttpServletRequest request) {
        String sessionId= request.getSession().getId();
        String tokenKey=TOKEN_NAME+sessionId;
        String token= UUID.randomUUID().toString();
        saveToken(tokenKey,token);
        return token;
    }

    @Override
    public void saveToken(String key,String token) {
        redisService.saveMinte(key,token,TOKEN_SAVE_TIME,true);
    }

    @Override
    public Boolean validateToken(HttpServletRequest request,String token) {
        if (StringUtils.isEmpty(token)){
            return false;
        }
        String key=request.getSession().getId();
        key= TOKEN_NAME+key;
        String currentToken= redisService.getBykey(key);
        if (StringUtils.isEmpty(currentToken) || !currentToken.equals(token)){
            return false;
        }
        redisService.delete(key);
        return true;
    }
}
